<template>
  <!-- <a-spin :spinning="loading"> -->
  <div class="detail-overview">
    <div class="content-search">
      <div class="content-search-left">
        <div
          v-for="item in regionList"
          class="btn-base"
          :class="{ 'btn-active': choiceRregion === item.id }"
          :key="item.id"
          @click="changeNetwork(item.id)"
        >
          {{ item.value }}
        </div>
      </div>
      <el-form layout="inline" style="text-align: right">
        <el-form-item label="VDC">
          <el-select v-model="searchForm.vdc" style="width: 150px" show-search>
            <el-option :value="'全部'">全部</el-option>
            <el-option v-for="(item, index) in vdcList" :key="index" :value="item">{{ item }}</el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="content-blcok">
      <div class="content-blcok-left">
        <div class="line-top" :style="styleBaseHeight()">
          {{ data.seq }}
        </div>
        <div class="line-center" id="scrollDiv">
          <div class="line-blcok" :style="styleBaseHeight(maxColumn)">
            <div class="line line-back" v-for="i in maxColumn" :key="i + 'none'" :style="styleBaseHeight()">
              <div class="line-left">{{ maxColumn - i + 1 }}</div>
              <div class="line-right"></div>
            </div>
            <div class="line line-content" v-for="(item, i) in allDataList" :key="i + 'item'" :style="getEquipStyle(item)">
              <div></div>
              <div class="line-right" v-if="['server', 'storage', 'switchboard'].includes(item.asset_type)">
                <el-popover placement="right" width="600">
                  <equipment-detail
                    :data="equipDataList[item.asset_no]"
                    :icon-name="item.asset_type"
                    :status-list="resourceStatusList(item.asset_type)"
                  ></equipment-detail>
                  <template #reference>
                    <div class="line-right-content" :class="{ 'line-right-content-active': ifActive(item) }">
                      <div class="content-icon">
                        <component :is="components[item.asset_type]" :color="statusColor[item['status']]"></component>
                      </div>
                      <div class="content-name">
                        {{ item.name }}
                      </div>
                    </div>
                  </template>
                </el-popover>
              </div>
              <div class="line-right" v-else>
                <div class="line-right-content" :class="{ 'line-right-content-active': ifActive(item) }">
                  <div class="content-icon">
                    <component :is="components[item.asset_type]" :color="statusColor[item['status']]"></component>
                  </div>
                  <div class="content-name">
                    {{ item.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="line-top" :style="styleBaseHeight()"></div>
      </div>
      <div class="content-blcok-right">
        <div class="echarts-item" v-for="(item, index) in echartsDataList" :key="index">
          <div v-if="index !== 0 && index !== 1" class="echarts-item-border"></div>
          <div class="echarts-item-title">{{ item.title }}</div>
          <div class="echarts-item-content">
            <EchartsPie :data="item.data" :color="item.colorList" :loading="echartsLoading"></EchartsPie>
          </div>
          <div class="echarts-item-label">
            <div v-for="(list, i) in item.data" :key="i" class="label-block">
              <div class="label-icon" :style="{ background: item.colorList[i] }"></div>
              <span>{{ list.level }}：</span>
              <span class="label-num" :style="{ color: item.colorList[i] }">{{ list.count }}</span>
              <span :style="{ color: item.colorList[i] }">台</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- </a-spin> -->
</template>

<script setup lang="ts">
import { ref, reactive, defineAsyncComponent, watch, computed, onMounted } from "vue";
import EchartsPie from "./Echarts.vue";
import EquipmentDetail from "./EquipmentDetail.vue";
import { _getFilterStatistic, _getResourceDetail, _getAssetDetailList } from "@/api/modules/asset/assetPanel";
import { ElMessage } from "element-plus";

const baseColor = reactive(["#0CB30C", "rgba(255, 195, 0, 1)", "rgba(232, 5, 5, 1)", "rgba(166, 166, 166, 1)"]);
const components = {
  secure: defineAsyncComponent(() => import("../icon/icon_secure.vue")),
  storage: defineAsyncComponent(() => import("../icon/icon_storage.vue")),
  server: defineAsyncComponent(() => import("../icon/icon_server.vue")),
  switchboard: defineAsyncComponent(() => import("../icon/icon_switchboard.vue")),
  others: defineAsyncComponent(() => import("../icon/icon_others.vue"))
};
const props = defineProps({
  data: {
    type: Object,
    require: true,
    default: () => ({})
  },
  centerId: {
    type: Number,
    require: true,
    default: 1
  }
});
const searchForm = ref({
  vdc: "全部"
});
let vdcList = ref([]);
const choiceRregion = ref(null);
const baseHegiht = ref<number>(24);
const maxColumn = ref<number>(47);
const statusList = reactive([
  {
    type: ["server", "storage"],
    data: {
      normal: { name: "正常", color: baseColor[0] },
      offline: { name: "离线", color: baseColor[1] },
      abnormal: { name: "故障", color: baseColor[2] },
      unknown: { name: "未知", color: baseColor[3] }
    }
  },
  {
    type: ["switchboard"],
    data: {
      normal: { name: "正常", color: baseColor[0] },
      offline: { name: "离线", color: baseColor[1] },
      unknown: { name: "未知", color: baseColor[3] }
    }
  },
  {
    type: ["secure", "others"],
    data: {
      unknown: { name: "未知", color: baseColor[3] }
    }
  },
  {
    type: ["cloud_host"],
    data: {
      normal: { name: "正常", color: baseColor[0] },
      abnormal: { name: "异常", color: baseColor[1] }, // 找不到的和不属于其他三个（normal、error、offline）都归为异常
      error: { name: "错误", color: baseColor[2] },
      offline: { name: "离线", color: baseColor[3] }
    }
  }
]);
const statusColor = reactive({
  green: baseColor[0],
  yellow: baseColor[1],
  red: baseColor[2],
  grey: baseColor[3]
});
let allDataList = reactive<any>([]);
let dataList = reactive([]);
const resourceList = reactive({
  server: "服务器",
  storage: "存储设备",
  switchboard: "交换机",
  secure: "安全设备",
  cloud_host: "云主机",
  others: "其他"
});
let echartsDataList = ref<any>([]);
let filterList = ref({});
let statisticList = reactive({});
const echartsLoading = ref(false);
const loading = ref(true);
let equipDataList = ref({});

const regionList = computed(() => {
  return filterList.value["region"] && filterList.value["region"]["value"] ? filterList.value["region"]["value"] : [];
});

watch(
  () => searchForm.value.vdc,
  () => {
    getAllDataList();
  }
);
watch(
  () => choiceRregion.value,
  () => {
    getAllDataList();
  }
);

const getFilterList = () => {
  filterList.value = {};
  _getFilterStatistic({})
    .then(res => {
      filterList.value = res.data;
    })
    .catch(err => {
      console.log(err);
    });
};

const getAllDataList = async () => {
  loading.value = true;
  echartsLoading.value = true;
  statisticList = {};
  const params = {
    rack_seq: props.data.seq,
    data_center_id: props.centerId,
    region_id: choiceRregion.value,
    vdc: searchForm.value.vdc
  };
  await _getResourceDetail(params)
    .then(async res => {
      const detail = res.data["detail"] || [];
      statisticList = res.data["statistic"] || {};
      // 查的全部数据
      if (params["vdc"] === "全部" && !params["region_id"]) {
        allDataList = detail;
        vdcList.value = res.data["vdc"] || [];
        dataList = [];
        await getAssetDetailList();
      } else {
        dataList = detail;
      }
      scrollLocate();
    })
    .catch(error => {
      console.log(error);
      let str = "机柜详情获取失败";
      if (error.response && error.response.data && error.response.data.message) {
        str += ": " + error.response.data.message;
      }
      ElMessage.error(str);
      loading.value = false;
      echartsLoading.value = false;
    });
  getEchartsDataList();
};
const ifActive = item => {
  return !!dataList.find(a => a["asset_no"] === item.asset_no);
};

const resourceStatusList = type => {
  const list = statusList.find(a => a.type.includes(type));
  return list ? list.data || {} : {};
};

// const resourceStatus = (type, status) => {
//   const statusList = resourceStatusList(type);
//   const list = statusList[status];
//   return list;
// };

// const resourceColor = (type, status) => {
//   return resourceStatus(type, status).color || baseColor[3];
// };

const styleBaseHeight = (count = 1) => {
  const style = {
    height: baseHegiht.value * count + "px"
  };
  return style;
};

const getEquipStyle = data => {
  return {
    bottom: (data["start_u"] - 1) * baseHegiht.value + "px",
    height: data["u_nums"] * baseHegiht.value + "px"
  };
};

const changeNetwork = key => {
  choiceRregion.value = choiceRregion.value === key ? undefined : key;
};

const getEchartsDataList = () => {
  echartsDataList.value = [];
  Object.keys(resourceList).forEach(key => {
    const statusList = resourceStatusList(key);
    let statistic = statisticList[key] || {};
    // 计算云主机的statistic
    if (key === "cloud_host") {
      let data = dataList;
      if (searchForm.value["vdc"] === "全部" && !choiceRregion.value) {
        data = allDataList;
      }
      let total = 0;
      let otherTotal = 0;
      statistic = {
        normal: 0,
        offline: 0,
        error: 0
      };
      data.forEach(a => {
        const hostList = equipDataList.value[a["asset_no"]] ? equipDataList.value[a["asset_no"]]["cloud_vm"] || [] : [];
        total += hostList.length;
        hostList.forEach(b => {
          if (Object.keys(statistic).includes(b["status"])) {
            statistic[b["status"]]++;
            otherTotal++;
          }
        });
      });
      statistic["abnormal"] = total - otherTotal;
    }
    const list: any = {
      title: resourceList[key],
      data: [],
      colorList: []
    };
    Object.keys(statusList).forEach(status => {
      list.data.push({
        level: statusList[status].name,
        count: statistic[status] || 0
      });
      list.colorList.push(statusList[status].color);
    });
    echartsDataList.value.push(list);
  });
  echartsLoading.value = false;
  loading.value = false;
};

const scrollLocate = () => {
  const element = document.getElementById("scrollDiv");
  // 定位到页面第一条数据，也就是dataList中最后一条数据
  let dataTop = 0;
  // if (dataList.length && dataList.length !== allDataList.length) {
  if (dataList.length) {
    const data = dataList[dataList.length - 1];
    dataTop = baseHegiht.value * maxColumn.value - (data["start_u"] + data["u_nums"]) * baseHegiht.value;
  }
  setTimeout(() => {
    if (element) {
      element.scrollTop = dataTop;
    }
  }, 0);
};

const getAssetDetailList = async () => {
  equipDataList.value = {};
  const assets = allDataList.map(a => {
    return a["asset_no"];
  });
  if (!assets.length) {
    return;
  }
  await _getAssetDetailList({ assets })
    .then(res => {
      const data: any = res.data || [];
      data.forEach(item => {
        equipDataList.value[item.asset_number] = item;
      });
    })
    .catch(error => {
      console.log(error);
      let str = "设备详情获取失败";
      if (error.response && error.response.data && error.response.data.message) {
        str += ": " + error.response.data.message;
      }
      ElMessage.error(str);
    });
};
onMounted(() => {
  getFilterList();
  getAllDataList();
});
</script>

<style lang="scss" scoped>
:deep().el-form-item {
  display: block;
  padding: 0;
  margin: 0;
}
:deep().el-form-item--default .el-form-item__content {
  display: inline-block;
}
.detail-overview {
  display: flex;
  flex-direction: column;
  gap: 24px;
  width: 100%;
  height: 680px;
  max-height: 680px;
  .content-blcok {
    display: grid;
    flex: 1;
    grid-template-columns: 280px auto;
    column-gap: 32px;
    min-height: 0;
    .content-blcok-left {
      display: flex;
      flex-direction: column;
      min-height: 0;
      .line-top {
        display: flex;
        align-items: center;
        justify-content: center;
        background: var(--el-bg-color-page);
        box-shadow: 0 0 1px var(--el-icon-color);
      }
      .line-center {
        flex: 1;
        overflow: hidden auto;
        .line-blcok {
          position: relative;
          .line {
            display: grid;
            grid-template-columns: 25px auto;
          }
          .line-back {
            .line-left {
              display: flex;
              align-items: center;
              justify-content: center;
              background: var(--el-bg-color-page);
              border-right: 1px solid var(--el-border-color);
              border-bottom: 1px solid var(--el-border-color);
            }
            .line-right {
              border-bottom: 1px solid var(--el-border-color);
            }
          }
          .line-content {
            position: absolute;
            left: 0;
            width: 100%;
            .line-right {
              min-width: 0;
              background: var(--el-bg-color);
              border-bottom: 1px solid var(--el-border-color);
              .line-right-content {
                display: flex;
                align-items: center;
                width: 100%;
                height: 100%;
                cursor: pointer;
                background: linear-gradient(90deg, var(--el-color-primary-light-7) 0%, var(--el-menu-hover-bg-color) 100%);
                box-shadow: 0 0 5px var(--el-icon-color);
                .content-icon {
                  display: flex;
                  width: 16px;
                  height: 16px;
                  margin: 0 16px;
                  svg {
                    width: 100%;
                    height: 100%;
                  }
                }
                .content-name {
                  flex: 1;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }
              }
              .line-right-content:hover {
                // box-shadow: 2px 6px 5px rgba(126, 186, 245, 0.8);
                border: 2px solid var(--el-color-primary-light-4);
              }
              .line-right-content-active {
                border: 2px solid var(--el-color-primary-light-4);
                box-shadow: 2px 6px 5px var(--el-color-primary-light-4);
              }
            }
          }
        }
      }
    }
    .content-blcok-right {
      display: grid;
      grid-template-rows: 1.1fr 1.2fr 1.2fr;
      grid-template-columns: repeat(2, 1fr);
      column-gap: 54px;
      .echarts-item {
        .echarts-item-border {
          height: 20px;
          border-top: 1px dashed var(--el-text-color3);
        }
        .echarts-item-content {
          height: 100px;
        }
        .echarts-item-label {
          display: grid;
          grid-template-rows: repeat(2, 1fr);
          grid-template-columns: repeat(2, 1fr);
          column-gap: 18px;
          height: 50px;
          padding: 0 6px;
          .label-block {
            display: flex;
            align-items: center;
            .label-icon {
              width: 6px;
              height: 6px;
              margin-right: 6px;
              border-radius: 6px;
            }
            .label-num {
              flex: 1;
              font-weight: 700;
            }
          }
        }
      }
    }
  }
  .content-title {
    font-size: 16px;
  }
  .content-search {
    display: grid;
    grid-template-columns: 1fr 250px;
    gap: 10px;
    .content-search-left {
      display: flex;
      gap: 10px;
      .btn-base {
        padding: 6px 12px;
        color: white;
        cursor: pointer;
        background: var(--el-color-primary-light-4);
        border-radius: 3px;
        box-shadow: 0 0 2px var(--el-icon-color);
      }
      .btn-active {
        background: var(--el-color-primary-light-2);
      }
      .btn-base:hover {
        background: var(--el-color-primary-light-2);
      }
    }
  }
}
.line-center::-webkit-scrollbar {
  width: 16px;
}

// .line-center::-webkit-scrollbar-button {
// background: red;
// }
.line-center::-webkit-scrollbar-track {
  background: var(--el-bg-color-page);
  border-radius: 0;
}
.line-center::-webkit-scrollbar-thumb {
  // background: #bfbfbf;
  background: var(--el-border-color);
  border-radius: 0;
}
.line-center::-webkit-scrollbar-thumb:hover {
  background: var(--el-icon-color);
}
.line-center::-webkit-scrollbar-corner {
  background: var(--el-color-primary);
}
</style>
